use core::time;

use chrono::{NaiveDate,Local};
use serde::{Deserialize, Serialize};
use rand::Rng;

use tauri::{Emitter, Manager, Window};
// Learn more about Tauri commands at https://tauri.app/v1/guides/features/command
#[tauri::command]
fn greet(name: &str) -> String {
    format!("Hello, {}! You've been greeted from Rust!", name)
}

#[tauri::command]
fn vaild(name: &str,pwd: &str) -> bool{
    match name {
        "admin" =>{
            if pwd == "123"{
                true
            }
            else{
                false
            }
        }
        _=>{
            if name == pwd {
                true
            }
            else{
                false
            }
        }
    }
}
#[derive(Debug, Serialize, Deserialize)]
enum Blood_Type{
    A,
    B,
    O,
    AB,
    Rh
}

#[derive(Debug, Serialize, Deserialize)]
struct user_info{
    username: String,
    nickname: String,
    email:String,
    age: u16,
    birthday: String,
    blood_type:Blood_Type,
    other:Vec<f32>,

}
#[tauri::command]
fn get_user_info(username:&str)-> user_info{
    user_info{
        username: username.to_owned(),
        nickname: "昵称".to_owned(),
        email: "abcd@abde.com".to_owned(),
        age: 35,
        birthday: NaiveDate::from_ymd_opt(1999, 8, 16).unwrap().to_string(),
        blood_type: Blood_Type::A,
        other: vec![1.5,2.0,3.3,3.1,2.6]
    }
}

#[tauri::command]
fn set_user_info(user:user_info)-> bool{
    println!("{:?}",user);
    true
}

#[derive(Clone,serde::Serialize)]
struct Payload{
    Proc_progress:i32,
    timestamp: String,
}
#[tauri::command]
fn send_message(window:Window){
    let mut proc = 0;
    let mut rng = rand::thread_rng();
    let mut is_continue: bool = true;
    while is_continue {
        window.emit(
            "proc_event",
            Payload{
                Proc_progress: proc,
                timestamp: Local::now().format("%Y-%m-%d %H:%M:%S").to_string(),
            },
        ).unwrap();
        
        if proc >= 100{
            proc = 100;
            is_continue = false;
        }
        else{
            let random_number = rng.gen_range(1..=10);
            proc = proc + random_number;
        }
        std::thread::sleep(time::Duration::from_secs(1));
    }
}

#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
    tauri::Builder::default()
        .plugin(tauri_plugin_shell::init())
        .invoke_handler(tauri::generate_handler![greet])
        .invoke_handler(tauri::generate_handler![vaild])
        .invoke_handler(tauri::generate_handler![get_user_info])
        .invoke_handler(tauri::generate_handler![set_user_info])
        .invoke_handler(tauri::generate_handler![send_message])
        .run(tauri::generate_context!())
        .expect("error while running tauri application");
}

#[cfg(test)]
mod tests{
    use super::*;

    #[test]
    fn test_get_user_info(){
        let x = get_user_info("abcd");
        println!("{:?}",x);
    }
}